<template>
  <el-dialog :close-on-click-modal="false" :before-close="handleBeforeClose" :visible=true 
    :title="title" width="800px">
    <el-form ref="form" :model="form" size="small" :disabled="disabled">
      <div ref="pdfContent">
        <el-table :data="tableData" style="width: 100%; margin-bottom: 20px;">
          <el-table-column prop="item" label="项目" width="120" />
          <el-table-column label="顺时针 90°">
            <template #default="scope">
              <el-input v-model="scope.row.qtSsz" type="number"/>
            </template>
          </el-table-column>
          <el-table-column label="逆时针 90°">
            <template #default="scope">
              <el-input v-model="scope.row.qtNsz" type="number"/>
            </template>
          </el-table-column>
          <el-table-column label="头右倾">
            <template #default="scope">
              <el-input v-model="scope.row.qtTyq" type="number"/>
            </template>
          </el-table-column>
          <el-table-column label="头左倾">
            <template #default="scope">
              <el-input v-model="scope.row.qtTzq" type="number"/>
            </template>
          </el-table-column>
          <el-table-column label="前低头">
            <template #default="scope">
              <el-input v-model="scope.row.qtQdt" type="number"/>
            </template>
          </el-table-column>
          <el-table-column label="直立">
            <template #default="scope">
              <el-input v-model="scope.row.qtZl" type="number"/>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="知识掌握">
          <el-select
            v-model="form.zszw"
            placeholder="请选择"
          >
            <el-option
              v-for="[key, value] in skillLevels"
              :key="value"
              :label="value"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="建议">
          <el-input v-model="form.jy"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="评定结果">
              <el-select
                v-model="form.result"
                placeholder="请选择"
              >
                <el-option
                  v-for="[key, value] in resultOptions"
                  :key="value"
                  :label="value"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录人" prop="createBy">
              <el-input v-model="form.createBy" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录日期" prop="createTime">
              <el-date-picker v-model="form.createTime" :picker-options="pickerOptions" type="datetime" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleCommit" :disabled="disabled">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {get, add, edit} from '@/api/trainQtcjmn'
import { RATE_RESULTS, SKILL_LEVELS} from '@/utils/constants'
import { table2Form, form2Table } from '../../../utils/table';
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

export default {
  name: 'QtcjmnDialog',
  props: {
    trainId: {
      type: Number,
      default: -1,
      required: true
    },
    itemId: {
      type: Number,
      default: -1,
      required: true
    },
    pilot: {
      type: Object,
      default: null
    }
  },
  computed: {
    disabled() {
      return this.form.id != null && !this.checkPer(['admin']);
    }
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }]
      },
      form: { id: null, trainId: null, trainItemId: null, zszw: null, result: null, jy: null, createBy: null, date: null },
      tableData: [
        { item: '自我空间感觉', qtSsz: '', qtNsz: '', qtTyq: '', qtTzq: '', qtQdt: '', qtZl: ''},
        { item: '持续时间', qtSsz: '', qtNsz: '', qtTyq: '', qtTzq: '', qtQdt: '', qtZl: ''},
      ],
      title: '前庭错觉模拟体验',
      skillLevels: SKILL_LEVELS,
      resultOptions: RATE_RESULTS,
      isLoading: false // 提交按钮的加载状态
    };
  },
  methods: {
    handleBeforeClose(done) {
      this.$emit('close', this.itemId);
      if (done) {
        done(); // 调用done()来关闭对话框        
      }
    },
    handleCommit() {
      // 同步tableData到form
      table2Form(this.tableData, this.form, 'qt');
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.isLoading = true; // 提交按钮的加载状态
          this.form.trainId = this.trainId;
          this.form.trainItemId = this.itemId;
          if (this.form.id == null) {
            add(this.form).then(() => {
              this.$emit('close', this.itemId);
              this.isLoading = false;
            }).catch(() => {
              this.isLoading = false;
            });
          } else {
            edit(this.form).then(() => {
              this.$emit('close', this.itemId);
              this.isLoading = false;
            }).catch(() => {
              this.isLoading = false;
            });
          }
        }
      })
    },
    handleCancel() {
      this.$emit('cancel', this.itemId);
    },
    async exportPDF() {
      try {
        const content = this.$refs.pdfContent;
        if (!content) {
          this.$message.error('未找到导出内容');
          return;
        }
        const canvas = await html2canvas(content, { scale: 2 });
        const imgData = canvas.toDataURL('image/jpeg', 1.0);
        const pdf = new jsPDF('p', 'mm', 'a4');
        // 计算图片宽高自适应A4
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        const imgWidth = pageWidth;
        const imgHeight = canvas.height * (imgWidth / canvas.width);
        let position = 0;
        if (imgHeight < pageHeight) {
          pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
        } else {
          // 多页处理
          let leftHeight = imgHeight;
          let pageData = imgData;
          while (leftHeight > 0) {
            pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            if (leftHeight > 0) {
              pdf.addPage();
              position = 0;
            }
          }
        }
        const pilotName = this.pilot ? this.pilot.name : '未知';
        pdf.save(`前庭错觉模拟体验-${pilotName}-导出.pdf`);
      } catch (e) {
        this.$message.error('导出失败: ' + e.message);
      }
    }
  },
  created() {
    console.log(this.trainId, this.itemId);
    if (this.trainId !== -1) {
      this.shouldUpdate = false;
      get(this.trainId, this.itemId).then(response => {
        this.form = Object.assign(this.form, response);
        form2Table(this.form, this.tableData, 'qt');
        console.log(response, this.form);
      });
    }
  },
  updated() {
  },
  mounted() {
  }
}
</script>

<style scoped>
</style>